package com.slipper.core.gson;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.slipper.util.Tool;

import java.lang.reflect.Type;
import java.util.Map;

public class GsonUtil {
    public static Gson getInstance() {
        return new GsonBuilder()
                .disableHtmlEscaping()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setStrictness(Strictness.LENIENT)
                .setExclusionStrategies(new GsonExclusionStrategy())
                .registerTypeAdapter(String.class, new StringTypeAdapter())
                .registerTypeAdapter(java.util.Date.class, new UtilDateTypeAdapter())
                .registerTypeAdapter(java.sql.Date.class, new SqlDateTypeAdapter())
                .registerTypeAdapter(java.time.LocalDateTime.class, new LocalDateTimeTypeAdapter())
                .registerTypeAdapter(Map.class, (JsonDeserializer<Map<String, Object>>) (json, typeOfT, context) -> new Gson().fromJson(json, typeOfT))
                .serializeNulls()
                .create();
    }
    
    public static String toJson(Object object) {
        if (object == null) return null;
        return getInstance().toJson(object);
    }

    public static Map<String, Object> toMap(String json) {
        if (Tool.isBlank(json)) return null;
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        return getInstance().fromJson(json, type);
    }

    public static <T> T toBean(String json, Class<T> clazz) {
        return getInstance().fromJson(json, clazz);
    }
    
    public static <T> T fromJson(String json, Type type) {
        return getInstance().fromJson(json, type);
    }

    public static <T> T fromJson(String json, Type type, T defaultValue) {
        if (Tool.isBlank(json)) {
            return defaultValue;
        }

        return getInstance().fromJson(json, type);
    }
}
